package com.taotao.order.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.taotao.common.pojo.TaotaoResult;
import com.taotao.mapper.TbOrderItemMapper;
import com.taotao.mapper.TbOrderMapper;
import com.taotao.mapper.TbOrderShippingMapper;
import com.taotao.order.jedis.JedisClient;
import com.taotao.order.pojo.OrderInfo;
import com.taotao.order.service.OrderService;
import com.taotao.pojo.TbOrderItem;
import com.taotao.pojo.TbOrderShipping;

/**
 * 订单的服务
 * @title OrderInterface
 * <p>description</p>
 * <p>company: www.itheima.com</p>
 * @author 天火
 * @version 1.0
 */
@Service
public class OrderServiceImpl implements OrderService {
	
	@Autowired
	private JedisClient client;
	
	@Autowired
	private TbOrderMapper tbOrderMapper;
	
	@Autowired
	private TbOrderItemMapper tbOrderItemMapper;
	
	@Autowired
	private TbOrderShippingMapper tbOSHMapper;
	
	@Value("${GEN_ORDER_ID_KEY}")
	private String GEN_ORDER_ID_KEY;
	
	@Value("${GEN_ORDER_ID_INIT}")
	private String GEN_ORDER_ID_INIT;

	@Value("${GEN_ORDER_ITEM_ID_KEY}")
	private String GEN_ORDER_ITEM_ID_KEY;
	
	@Override
	public TaotaoResult createOrder(OrderInfo orderInfo) {
		// 1.插入订单表
			//通过redis.incr生成Id
		//判断如果Key没有存在，需要初始化一个Key值来设置初始值
		if(!client.exists(GEN_ORDER_ID_KEY)) {
			client.set(GEN_ORDER_ID_KEY, GEN_ORDER_ID_INIT);
		}
		String orderId = client.incr(GEN_ORDER_ID_KEY).toString();
		//orderInfo.setBuyerNick(buyerNick); controller设置用户名称
			//补全其他的属性
		orderInfo.setOrderId(orderId);
		orderInfo.setPostFee("0");
		orderInfo.setStatus(1);
		//orderInfo.setUserId(userId);   controller设置用户名称
		orderInfo.setUpdateTime(orderInfo.getCreateTime());
		//注入mapper
		tbOrderMapper.insert(orderInfo);
		//2.插入订单项表
			//设置订单项Id  通过redis.incr生成Id
			//补全其他属性
		List<TbOrderItem> orderItems = orderInfo.getOrderItems();
		for(TbOrderItem tbOrderItem :orderItems){
			String incr = client.incr(GEN_ORDER_ITEM_ID_KEY).toString();
			tbOrderItem.setId(incr);
			tbOrderItem.setOrderId(orderId);
			//插入订单项表
			tbOrderItemMapper.insert(tbOrderItem);
		}
		//3.插入订单物流表
			//设置订单Id
		TbOrderShipping shipping = orderInfo.getOrderShipping();
		//补全其他属性
		shipping.setOrderId(orderId);
		shipping.setUpdated(orderInfo.getCreateTime());
		shipping.setCreated(orderInfo.getCreateTime());
		
		//插入
		tbOSHMapper.insert(shipping);
		return TaotaoResult.ok(orderId);
	}
	

}
